package com.ai.chat.controller;

/**
 * ClassName:    ChatController
 * Description:  TODO
 * Author:       yuzx
 * Date:         2025/9/8 14:29
 * Version:      1.0
 **/

import com.ai.chat.domain.ChatMessage;
import com.ai.chat.service.IChatService;
import com.ai.common.core.controller.BaseController;
import com.ai.common.core.domain.AjaxResult;
import com.ai.common.core.domain.model.LoginUser;
import com.ai.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

/**
 * 聊天控制器
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/ai/chat")
public class ChatController extends BaseController {

    @Autowired
    private IChatService chatService;

    /**
     * 发送消息
     */
    @PostMapping("/send")
    public AjaxResult sendMessage(@RequestBody Map<String, String> request) {
        try {
            // 获取当前登录用户ID
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = loginUser.getUserId();

            // 获取请求内容
            String content = request.get("content");
            logger.info("用户[{}]发送消息: {}", userId, content);
            if (content == null || content.trim().isEmpty()) {
                return AjaxResult.error("消息内容不能为空");
            }

            // 调用服务发送消息
            String response = chatService.sendMessage(userId, content);
            logger.info("用户[{}]收到回复: {}", userId, response);
            return AjaxResult.success(response);
        } catch (Exception e) {
            logger.error("发送消息失败", e);
            return AjaxResult.error("发送消息失败: " + e.getMessage());
        }
    }

    /**
     * 清空聊天历史
     */
    @PostMapping("/clear")
    public AjaxResult clearHistory() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = loginUser.getUserId();

            chatService.clearHistory(userId);
            return AjaxResult.success("聊天历史已清空");
        } catch (Exception e) {
            logger.error("清空聊天历史失败", e);
            return AjaxResult.error("清空聊天历史失败: " + e.getMessage());
        }
    }

    /**
     * 获取聊天历史
     */
    @GetMapping("/history")
    public AjaxResult getHistory() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            Long userId = loginUser.getUserId();

            List<ChatMessage> history = chatService.getHistory(userId);
            logger.info("用户[{}]的聊天历史: {}", userId, history);
            return AjaxResult.success(history);
        } catch (Exception e) {
            logger.error("获取聊天历史失败", e);
            return AjaxResult.error("获取聊天历史失败: " + e.getMessage());
        }
    }
}
